package com.huan.juejin.task;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * 处理掘金的自动签到和抽奖
 *
 * @author huan.fu 2021/11/18 - 下午5:10
 */
@Component
public class JuejinTask {
    
    private static final Logger log = LoggerFactory.getLogger(JuejinTask.class);
    
    private static final String CHECK_IN = "https://api.juejin.cn/growth_api/v1/check_in";
    private static final String LOTTERY = "https://api.juejin.cn//growth_api/v1/lottery/draw";
    
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private JavaMailSender javaMailSender;
    
    @Scheduled(cron = "0 30 8 * * ?")
    @PostConstruct
    public void invoked() {
        try {
            // 1、签到
            Booleans signInResult = signIn();
            if (!signInResult.success) {
                log.warn("当前不是签到成功,不进行抽奖操作");
                // 发送邮件
                sendEmail(signInResult.result);
                return;
            }
            // 2、抽奖
            String lotteryResult = lottery();
            // 3、发送邮件
            sendEmail(lotteryResult);
        } catch (Exception e) {
            // 发送邮件
            sendEmail(e.getMessage());
        }
    }
    
    private void sendEmail(String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("1451578387@qq.com");
        message.setTo("it_java_software@163.com");
        message.setSubject("掘金签到抽奖");
        message.setText(content);
        javaMailSender.send(message);
        log.info("邮件发送成功");
    }
    
    public String lottery() {
        String result = restTemplate.postForObject(LOTTERY, null, String.class);
        log.info("抽奖结果:[{}]", result);
        return result;
    }
    
    public Booleans signIn() throws JsonProcessingException {
        String result = restTemplate.postForObject(CHECK_IN, null, String.class);
        log.info("签到结果:[{}]", result);
        Map map = new ObjectMapper().readValue(result, Map.class);
        boolean signInSuccess = (int) map.get("err_no") == 0;
        return new Booleans(signInSuccess, result);
    }
    
    public static class Booleans {
        public boolean success;
        public String result;
        
        public Booleans(boolean success, String result) {
            this.success = success;
            this.result = result;
        }
    }
}
